import Flutter
import UIKit

public class SecureStorePlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "plugin_secure_store", binaryMessenger: registrar.messenger())
    let instance = SecureStorePlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "generateRSA":
        let params = call.arguments as? Dictionary<String, String>
        let alias = params?["alias"]
        if alias == nil || alias == "" {
            result(FlutterError(code: "1", message: "别名为空!", details: ""))
            return
        }

//        let pubKey = KeyStoreManager.instance.generateRSA(alias!)
//        if pubKey != nil {
//            result(pubKey?.base64EncodedString().trimmingCharacters(in: .whitespaces))
//        } else {
//            result(FlutterError(code: "2", message: "密钥生成失败!", details: ""))
//        }
        
        let nData = KeyStoreManager.instance.generateRSAByModulus(alias!)
        if let nHex = nData, nData?.count ?? 0 >= 256 {
            // nHex 的前 256 是E值, 后 10 是N值
            let endIndex = nHex.index(nHex.startIndex, offsetBy: 256)  // 获取结束索引
            result("n:" + nHex[nHex.startIndex ..< endIndex]) // n: 是同服务端加密方协商的iOS端公钥N值的标识(Android端直接传的Base64编码的完整公钥)
        } else {
            result(FlutterError(code: "2", message: "密钥生成失败!", details: ""))
        }
    case "encryptRSA":
        let params = call.arguments as? Dictionary<String, String>
        let alias = params?["alias"]
        let content = params?["content"]
        if alias == nil || alias == "" {
            result(FlutterError(code: "1", message: "别名为空!", details: ""))
            return
        }
        if content == nil || content == "" {
            result(FlutterError(code: "1", message: "加密的数据不能为空!", details: ""))
            return
        }
        
        let resultEncrypt = KeyStoreManager.instance.encryptRSA(alias!, content!)
        if resultEncrypt != nil {
            result(resultEncrypt)
        } else {
            result(FlutterError(code: "2", message: "加密失败!", details: ""))
        }
    case "decryptRSA":
        let params = call.arguments as? Dictionary<String, String>
        let alias = params?["alias"]
        let content = params?["content"]
        if alias == nil || alias == "" {
            result(FlutterError(code: "1", message: "别名为空!", details: ""))
          return
        }
        if content == nil || content == "" {
            result(FlutterError(code: "1", message: "解密的数据不能为空!", details: ""))
            return
        }
        
        let resultDecrypt = KeyStoreManager.instance.decryptRSA(alias!, content!)
        if resultDecrypt != nil {
            result(resultDecrypt)
        } else {
            result(FlutterError(code: "2", message: "解密失败!", details: ""))
        }
    case "decryptBigRSA":
        let params = call.arguments as? Dictionary<String, String>
        let alias = params?["alias"]
        let content = params?["content"]
        if alias == nil || alias == "" {
            result(FlutterError(code: "1", message: "别名为空!", details: ""))
          return
        }
        if content == nil || content == "" {
            result(FlutterError(code: "1", message: "分段解密的数据不能为空!", details: ""))
            return
        }
        let resultDecrypt = KeyStoreManager.instance.decryptBigRSA(alias!, content!)
        if resultDecrypt != nil {
            result(resultDecrypt)
        } else {
            result(FlutterError(code: "2", message: "分段解密失败!", details: ""))
        }
    default:
      result(FlutterMethodNotImplemented)
    }
  }
    
  
    
}

extension Data {
    /// MARK: Data转十六进制字符串
    /// Create hexadecimal string representation of `Data` object.
    /// - returns: `String` representation of this `Data` object.
    func toHexString() -> String {
        return map { String(format: "%02x", $0) }
            .joined(separator: "")
//            .joined(separator: "-")
    }
}
